package com.shenma2009.netty.client;

/**
 * @author Administrator
 * @version 1.0
 * @description: TODO
 * @date 2023/7/4 0004 9:44
 */

import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import javax.websocket.*;

@ClientEndpoint
public class VehicleWebSocketClient {

    private Session session;

    @OnOpen
    public void onOpen(Session session) {
        this.session = session;
    }

    @OnMessage
    public void onMessage(String message, Session session) {
        // 处理接收到的消息
        System.out.println("Received message from server: " + message);
    }

    public void sendPositionData(String data) throws IOException {
        session.getBasicRemote().sendText(data);
    }

    public static void main(String[] args) {
        WebSocketContainer container = ContainerProvider.getWebSocketContainer();

        try {
            String serverUri = "ws://localhost:8080/vehicle";
            VehicleWebSocketClient client = new VehicleWebSocketClient();
            container.connectToServer(client, new URI(serverUri));

            // 定期发送位置数据
            String positionData = "{'latitude': 37.12345, 'longitude': -122.67890}";
            client.sendPositionData(positionData);

        } catch (URISyntaxException | IOException e) {
            e.printStackTrace();
        } catch (DeploymentException e) {
            throw new RuntimeException(e);
        }
    }
}
